<template>
  <div class="app-container">
    <!-- 查询表单 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="SKU编码" prop="sku">
        <el-input
          v-model="queryParams.sku"
          placeholder="请输入SKU编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="产品名称" prop="productName">
        <el-input
          v-model="queryParams.productName"
          placeholder="请输入产品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属店铺" prop="shopId">
        <el-select v-model="queryParams.shopId" placeholder="请选择店铺" clearable>
          <el-option
            v-for="item in shopOptions"
            :key="item.shopId"
            :label="item.shopName"
            :value="item.shopId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="利润率" prop="profitRateRange">
        <el-select v-model="queryParams.profitRateRange" placeholder="请选择利润率范围" clearable>
          <el-option label="30%以下" value="low" />
          <el-option label="30%-50%" value="medium" />
          <el-option label="50%以上" value="high" />
        </el-select>
      </el-form-item>
      <el-form-item label="回款日期" prop="dateRange">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          clearable
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['profit:statistics:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stat-cards mb8">
      <el-col :span="6">
        <div class="stat-card">
          <div class="stat-icon" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);">
            <i class="el-icon-coin"></i>
          </div>
          <div class="stat-content">
            <div class="stat-label">总利润</div>
            <div class="stat-value" :style="totalProfit >= 0 ? 'color: #67C23A' : 'color: #F56C6C'">
              ¥{{ totalProfit.toFixed(2) }}
            </div>
          </div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="stat-card">
          <div class="stat-icon" style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);">
            <i class="el-icon-s-finance"></i>
          </div>
          <div class="stat-content">
            <div class="stat-label">总收入</div>
            <div class="stat-value">¥{{ totalIncome.toFixed(2) }}</div>
          </div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="stat-card">
          <div class="stat-icon" style="background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);">
            <i class="el-icon-s-data"></i>
          </div>
          <div class="stat-content">
            <div class="stat-label">总成本</div>
            <div class="stat-value">¥{{ totalCost.toFixed(2) }}</div>
          </div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="stat-card">
          <div class="stat-icon" style="background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);">
            <i class="el-icon-pie-chart"></i>
          </div>
          <div class="stat-content">
            <div class="stat-label">平均利润率</div>
            <div class="stat-value">{{ avgProfitRate.toFixed(2) }}%</div>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="statisticsList">
      <el-table-column label="SKU" align="center" prop="sku" width="140" :show-overflow-tooltip="true" fixed="left" />
      <el-table-column label="SKU货号" align="center" prop="skuCode" width="120" :show-overflow-tooltip="true" />
      <el-table-column label="产品名称" align="center" prop="productName" width="140" :show-overflow-tooltip="true" fixed="left" />
      <el-table-column label="SKU属性" align="center" prop="skuAttr" width="110" :show-overflow-tooltip="true" />
      <el-table-column label="备货总数量" align="center" prop="totalStockQuantity" width="110" />
      <el-table-column label="销售总数量" align="center" prop="totalSalesQuantity" width="110" />
      <el-table-column label="售后总数量" align="center" prop="totalAftersaleQuantity" width="110" />
      <el-table-column label="售后总金额" align="center" prop="totalAftersaleAmount" width="120">
        <template slot-scope="scope">
          <span style="color: #F56C6C;">{{ scope.row.totalAftersaleAmount != null && scope.row.totalAftersaleAmount > 0 ? '¥' + scope.row.totalAftersaleAmount.toFixed(2) : '¥0.00' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="产品单个平均成本" align="center" prop="productAvgCost" width="150">
        <template slot-scope="scope">
          <span>{{ scope.row.productAvgCost != null ? '¥' + scope.row.productAvgCost.toFixed(2) : '¥0.00' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="产品总成本" align="center" prop="productTotalCost" width="120">
        <template slot-scope="scope">
          <span style="font-weight: bold;">{{ scope.row.productTotalCost != null ? '¥' + scope.row.productTotalCost.toFixed(2) : '¥0.00' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="收入金额" align="center" prop="totalIncomeAmount" width="120">
        <template slot-scope="scope">
          <span style="color: #67C23A; font-weight: bold;">{{ scope.row.totalIncomeAmount != null ? '¥' + scope.row.totalIncomeAmount.toFixed(2) : '¥0.00' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="利润" align="center" prop="profit" width="120">
        <template slot-scope="scope">
          <span :style="getProfitStyle(scope.row.profit)">{{ scope.row.profit != null ? '¥' + scope.row.profit.toFixed(2) : '¥0.00' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="利润率(%)" align="center" prop="profitRate" width="110">
        <template slot-scope="scope">
          <el-tag :type="getProfitRateType(scope.row.profitRate)" effect="dark">
            {{ scope.row.profitRate != null ? scope.row.profitRate + '%' : '0%' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="所属店铺" align="center" prop="shopName" width="110" />
      <el-table-column label="产品状态" align="center" prop="productStatus" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.product_status" :value="scope.row.productStatus"/>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script>
import { listStatistics } from "@/api/business/profit"
import { getShopList } from "@/api/system/user"

export default {
  name: "ProfitStatistics",
  dicts: ['product_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 利润统计表格数据
      statisticsList: [],
      // 店铺选项
      shopOptions: [],
      // 统计数据
      totalProfit: 0,
      totalIncome: 0,
      totalCost: 0,
      avgProfitRate: 0,
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        sku: null,
        productName: null,
        shopId: null,
        profitRateRange: null,
        beginDate: null,
        endDate: null
      }
    }
  },
  created() {
    this.getList()
    this.getShopOptions()
  },
  methods: {
    /** 查询利润统计列表 */
    getList() {
      this.loading = true
      listStatistics(this.queryParams).then(response => {
        this.statisticsList = response.rows
        this.total = response.total
        
        // 提取统计数据
        if (response.summary) {
          this.totalProfit = response.summary.totalProfit || 0
          this.totalIncome = response.summary.totalIncome || 0
          this.totalCost = response.summary.totalCost || 0
          this.avgProfitRate = response.summary.avgProfitRate || 0
        }
        
        this.loading = false
      })
    },
    /** 获取店铺选项 */
    getShopOptions() {
      getShopList().then(response => {
        this.shopOptions = response.data
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      // 处理日期范围
      if (this.dateRange && this.dateRange.length === 2) {
        this.queryParams.beginDate = this.dateRange[0]
        this.queryParams.endDate = this.dateRange[1]
      } else {
        this.queryParams.beginDate = null
        this.queryParams.endDate = null
      }
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.resetForm("queryForm")
      this.handleQuery()
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('business/profit/statistics/export', {
        ...this.queryParams
      }, `利润统计_${new Date().getTime()}.xlsx`)
    },
    /**
     * 获取利润率标签类型（颜色标记）
     * <20% 红色，>50% 绿色，20%-50% 默认
     */
    getProfitRateType(profitRate) {
      if (profitRate == null) {
        return ''
      }
      if (profitRate < 20) {
        return 'danger'  // 红色
      } else if (profitRate > 50) {
        return 'success'  // 绿色
      } else {
        return 'warning'  // 橙色
      }
    },
    /**
     * 获取利润样式（负数红色，正数绿色）
     */
    getProfitStyle(profit) {
      if (profit == null) {
        return ''
      }
      if (profit < 0) {
        return 'color: #F56C6C; font-weight: bold;'  // 红色
      } else if (profit > 0) {
        return 'color: #67C23A; font-weight: bold;'  // 绿色
      } else {
        return 'font-weight: bold;'
      }
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

/* 统计卡片样式 */
.stat-cards {
  margin-bottom: 20px;
}

.stat-card {
  display: flex;
  align-items: center;
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transition: all 0.3s;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.15);
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
}

.stat-icon i {
  font-size: 28px;
  color: #fff;
}

.stat-content {
  flex: 1;
}

.stat-label {
  font-size: 14px;
  color: #909399;
  margin-bottom: 8px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}
</style>

